# 执行main方法
import argparse
from DataService import DataService
import pymysql
import time


def main():
    parser = argparse.ArgumentParser()
    # parser.add_argument("--phone", help="Phone number")
    parser.add_argument("--type", help="the model type's sign, such as 'zaixin_model_hq' or 'zaixin_model_zx' or 'zaixin_model_zf'")
    # 是否是继续执行
    parser.add_argument("--keep", help="是否继续执行")
    args = parser.parse_args()

    # 服务编码
    type = args.type
    if type is None:
        print("please input the type")
        return
    
    is_continue = False
    if args.keep is not None:
        is_continue = True

    # 服务编码 modelId=[zx|hq|zf] 
    # 装修 ：zaixin_model_zx zx 1026556 zaixin_zhuangxiu_rsltout_20240201.txt
    # 婚庆：zaixin_model_hq hq 87416 zaixin_hunqing_rsltout_20240201.txt
    # 支付：zaixin_model_zf zf 51908 zaixin_zhifu_rsltout_20240201.txt
    if type == "zx":
        modelId = "zaixin_model_zx"
        table_name = "data_zhuangxiu"
        month = "20240101"
    elif type == "hq":
        modelId = "zaixin_model_hq"
        table_name = "data_hunqing"
        month = "20240111"
    elif type == "zf":
        modelId = "zaixin_model_zf"
        table_name = "data_zhifu"
        month = "20240121"
    else:
        print("please input the correct type")
        return    
    
    dataService = DataService()
    dataService.get_apply_key()
    
    servCode = "EXTLAB-AA25"
    # 从数据库中获取数据
    # 创建数据库连接
    db = pymysql.connect(host='localhost', user='root', password='lcz19860109', db='dev10086', charset='utf8')
    cursor = db.cursor()
    
    # 错误日志目录
    errorLogDir = "/data/dev10086/result/"
    
    # 从table_name表中分批次获取所有数据
    # 定义每批次读取的数据量
    batch_size = 100
    offset = 0

    while True:
        # 从table_name表中获取一批数据
        if is_continue:
            cursor.execute(f"SELECT id,phone,month FROM {table_name} WHERE is_check=0 LIMIT {batch_size} OFFSET {offset}")
        else:
            cursor.execute(f"SELECT id,phone,month FROM {table_name} LIMIT {batch_size} OFFSET {offset}")
        results = cursor.fetchall()

        # 如果没有更多的数据，就退出循环
        if not results:
            break

        # 处理这批数据
        for row in results:
            id, phone, mon = row
            # 转成字符串
            mon = str(mon) + "01"
            requestXml = dataService.create_xml_phone(servCode, modelId, phone, month)
            # print(requestXml)
            responseXml = dataService.do_post(requestXml)
            # print(responseXml)
            # 解析responseXml
            # 如果ResponseCode=0，解析ServResult，保存结果
            responseRs = dataService.parse_xml(responseXml)
            rsCode, billing, value, is_valid = responseRs
            # rsCode=0表示成功
            if rsCode != "0":
                # 写入错误日志，type
                with open(f"{errorLogDir}{type}_error.log", "a") as f:
                    f.write(f"{id}|{phone}|{month}|{rsCode}\n")
                    
                sql = f"UPDATE {table_name} SET is_check=1 WHERE id={id}"
                cursor.execute(sql)
                db.commit()
                continue
            else:
                # 保存结果到数据库
                sql = f"UPDATE {table_name} SET is_billing={billing}, value={value}, is_valid={is_valid}, is_check=1 WHERE id={id}"
                cursor.execute(sql)
                db.commit()
                
            # sleep 20ms
            # time.sleep(0.02)
            
        # 更新偏移量，以便下次获取下一批数据
        offset += batch_size
    
    db.close()
                  
    # modelId = "ZAIXIN_MODEL_HQ"
    # uaid = "id_107053343"
    # mon = "202401"
    # requestXml = dataService.create_xml(servCode, modelId, uaid, mon)
    # print(requestXml)
    # responseXml = dataService.do_post(requestXml)
    # print(responseXml)
   
    
if __name__ == '__main__':
    main()